import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadio,
  ElRadioGroup,
  ElSpace,
  type FormInstance,
  type FormRules
} from 'element-plus'
import { isEmpty } from 'lodash-unified'
import { computed, defineComponent, reactive, toRefs } from 'vue'

import { configApi, type IConfigPageItem } from '@/apis'
import { objAssign } from '@/utils'

import {
  configDialogProps,
  formData,
  type IFormData
} from './ConfigDialog.define'

export default defineComponent({
  name: 'ConfigDialog',
  props: configDialogProps(),
  emits: ['success'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      formRef: {} as FormInstance,
      formModel: formData(),
      formRules: {
        configName: [{ required: true, message: '参数名称不能为空' }],
        configKey: [{ required: true, message: '参数键名不能为空' }],
        configValue: [{ required: true, message: '参数键值不能为空' }]
      } as FormRules<IFormData>,
      selectedRecord: {} as IConfigPageItem,
      submitLoading: false
    })

    const isAdd = computed(() => isEmpty(state.selectedRecord))

    const dialogTitle = computed(() =>
      isAdd.value ? '添加参数配置' : '修改参数配置'
    )

    function open(data = {} as IConfigPageItem) {
      state.selectedRecord = data
      objAssign(state.formModel, data)
      state.show = true
    }

    function handleClose() {
      state.show = false
      state.submitLoading = false
      state.selectedRecord = Object.create(null)
      state.formModel = formData()
      state.formRef.clearValidate()
    }

    function handleSubmit() {
      state.formRef.validate(async valid => {
        if (valid) {
          try {
            state.submitLoading = true

            if (isAdd.value) {
              await configApi.createConfig(state.formModel)
            } else {
              await configApi.updateConfig(
                state.selectedRecord.id,
                state.formModel
              )
            }

            handleClose()
            emit('success')
          } catch (error) {
            state.submitLoading = false
          }
        }
      })
    }

    return {
      ...toRefs(state),
      dialogTitle,
      open,
      handleClose,
      handleSubmit
    }
  },
  render() {
    return (
      <ElDialog
        v-model={this.show}
        title={this.dialogTitle}
        width="600px"
        destroyOnClose
        beforeClose={this.handleClose}
      >
        {{
          default: () => (
            <ElForm
              ref={(e: any) => (this.formRef = e)}
              model={this.formModel}
              rules={this.formRules}
              labelWidth="100px"
            >
              <ElFormItem label="参数名称" prop="configName">
                <ElInput
                  v-model={this.formModel.configName}
                  placeholder="请输入参数名称"
                />
              </ElFormItem>
              <ElFormItem label="参数键名" prop="configKey">
                <ElInput
                  v-model={this.formModel.configKey}
                  placeholder="请输入参数键名"
                />
              </ElFormItem>
              <ElFormItem label="参数键值" prop="configValue">
                <ElInput
                  v-model={this.formModel.configValue}
                  placeholder="请输入参数键值"
                />
              </ElFormItem>
              <ElFormItem label="系统内置" prop="configType">
                <ElRadioGroup v-model={this.formModel.configType}>
                  {this.ynOptions.map(v => (
                    <ElRadio key={v.value} value={v.value}>
                      {v.label}
                    </ElRadio>
                  ))}
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem label="备注" prop="remark">
                <ElInput
                  v-model={this.formModel.remark}
                  type="textarea"
                  rows={3}
                  placeholder="请输入内容"
                />
              </ElFormItem>
            </ElForm>
          ),
          footer: () => (
            <ElSpace>
              <ElButton onClick={this.handleClose}>取消</ElButton>
              <ElButton
                type="primary"
                loading={this.submitLoading}
                onClick={this.handleSubmit}
              >
                确定
              </ElButton>
            </ElSpace>
          )
        }}
      </ElDialog>
    )
  }
})
